package com.biz.primus.ms.commodity.dao.redis;

import com.biz.primus.base.redis.spi.ShardedJedisRedis;
import com.biz.primus.base.redis.util.RedisUtil;
import org.springframework.stereotype.Repository;

/**
 * 分布式锁
 */
@Repository
public class RedisLockRedisDao extends ShardedJedisRedis {

    private static final String KEY_PREFIX = "Biz:lock:";

    /**
     * 尝试加锁,如果返回true 加锁成功,反之失败
     * 如果加锁成功后的 timeOutSeconds 秒内,依然没有执行unLock操作,则会自动释放锁
     * 同一时间,只有一个线程可以拿到锁
     *
     * @param lockName
     * @param timeOutSeconds
     * @return
     */
    public boolean tryLock(String lockName, int timeOutSeconds) {
        String lockKey = getKey(lockName);
        boolean success = setnx(KEY_PREFIX + lockName, RedisUtil.toByteArray("lock"));
        if (success) {
            expire(lockKey, timeOutSeconds);
        }
        return success;
    }

    /**
     * 拿到锁 执行完成后 在finally中释放锁
     * @param lockName
     */
    public void unLock(String lockName) {
        del(getKey(lockName));
    }

    private String getKey(String lockName) {
        String result = KEY_PREFIX + lockName;
        return result;
    }
}
